package nju.mscs.businesslogic;

import java.util.ArrayList;


import nju.mscs.data.object.*;

public class RG implements ReturnGoods{
	private Database db;
	private Bill bill;
	private User cashier;
	private double money;
	private ReturnBill returnBill;
	private ArrayList<SaleGoods> returnList;
	private ArrayList<Goods> goodsList;
	public RG(){
		db=LogIn.db;
		cashier=LogIn.user;
	}
	public String[][] searchBill(String id){
		returnList=new ArrayList<SaleGoods>();
		goodsList=new ArrayList<Goods>();
		if((bill=db.searchBill(id))!=null){
			ArrayList<SaleGoods> sgl=bill.getGoodsList();
			ArrayList<ReturnBill> rl=bill.getRb();
			int n=sgl.size();
			String[][] result=new String[n+1][5];
			result[0][0]=bill.getTime().getTime().toString();
			int i=1;
			for(SaleGoods sg:sgl){
				result[i][0]=sg.getGoods().getId();
				result[i][1]=sg.getGoods().getName();
				result[i][2]=sg.getSum()+"";
				result[i][3]=sg.getDiscount()*sg.getGoods().getPrice()+"";
				for(ReturnBill rb:rl){
					if(rb.searchGoods(sg.getGoods().getId()))
						result[i][4]="已退";
					else
						result[i][4]="";
				}
			}
			return result;
		}
		else
			return null;
	}
	public String[] addGoods(String id){
		
		SaleGoods sg=bill.searchGoods(id);
		//System.out.println("A:"+returnList.size());
		if(sg!=null){
	 	returnList.add(sg);
	 	goodsList.add(sg.getGoods());
	 	Goods goods=sg.getGoods();
	 	String[] result={""+goods.getId(),goods.getName(),""+sg.getDiscount()*goods.getPrice(),};
	 	return result;
		}
		else
			return null;
	}
	@Override
	public boolean deleteGoods(String id) {
		// TODO Auto-generated method stub
		for(SaleGoods sg:returnList){
			if(sg.getGoods().getId().equals(id)){
				returnList.remove(sg);
				goodsList.remove(sg.getGoods());
			}
		}
		return true;
	}
	public double returnMoney(){
		double sum=0;
		System.out.println(returnList.size());
		for(SaleGoods sg:returnList){
			System.out.println(sg.getGoods().getName());
			sum+=sg.getGoods().getPrice()*sg.getDiscount();
		}
		sum=Math.round(sum*100.0)/100.0;
		return sum;
	}
	public boolean returning(){
		returnBill=bill.creatReturnBill(cashier, goodsList, money);
		int n=(int)money/10;
		VipConsumer vip=bill.getVip();
		if(vip!=null){
		vip.addSumPoints(-n);
		db.requsetChangerVipPoint(vip.getId(), -n,0);
		}
		takeReceipts();
		return true;
	}
	private void takeReceipts(){
		returnBill.print();
	}
	
	
	//测试用方法
	public void setData(Database d){
		db=d;
	}
	
}